package com.library.lms.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.pagehelper.PageInfo;
import com.library.lms.config.OssClientConfig;
import com.library.lms.entity.Books;
import com.library.lms.entity.BooksBorrow;
import com.library.lms.service.BooksBorrowService;
import com.library.lms.service.BooksService;
import com.library.lms.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/books")
public class booksController {
    @Autowired
    private BooksService booksService;

    @Autowired
    public OssClientConfig ossClientConfig;

    @Autowired
    public BooksBorrowService booksBorrowService;

    @PostMapping("/addbooks")
    public Map<String, String> addbook(@RequestBody Books books) {
        Map<String, String> map = new HashMap<>();
        int i = booksService.addBooks(books);
        log.info("books里面有什么【{}】", books);
        map.put("msg", "success");
        return map;
    }
    @PostMapping("/ebook")
    public Map<String, String> editbook(@RequestBody Books books) {
        Map<String, String> map = new HashMap<>();
        int i = booksService.editBook(books);
        if (i == 1) {
            log.info("books里面有什么【{}】", books);
            map.put("msg", "success");
            return map;
        }
        map.put("msg", "error");
        return map;
    }

    @PostMapping("/upload")
    public Map<String, String> upload(@RequestParam("file") MultipartFile file) throws IOException {
        log.info(file.getOriginalFilename());
        Map<String, String> map = new HashMap<>();
        String accessKeyId = ossClientConfig.getAccessKeyId();
        String endpoint = ossClientConfig.getEndpoint();
        String accessKeySecret = ossClientConfig.getAccessKeySecret();
        String bucketName = ossClientConfig.getBucketName();
        try {
            //创建OSSClient实例
            OSS OssBuild = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //上传文件流
            ByteArrayInputStream inputStream1 = new ByteArrayInputStream(file.getBytes());
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.indexOf('.'));
            //uuid生成新名字
            //String newName = UUID.randomUUID() + substring;
            //时间文件名
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String newName = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter) + substring;
            //调用oss上传
            OssBuild.putObject(bucketName, newName, inputStream);
            //关闭文件流
            OssBuild.shutdown();
            //返回上传之后的链接
            String url = "https://" + bucketName + "." + endpoint + "/" + newName;
            map.put("msg", "success");
            map.put("img", url);
            log.info("图片url【{}】", url);

        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "error");
            return map;
        }

        return map;

    }

    @GetMapping("/booklist")
    public ResultVo<List<Books>> books() {
        Map<String, Object> map = new HashMap<>();

        List<Books> books = booksService.queryBooks();

        return new ResultVo<>(books).success();
    }

    @PostMapping("/query")
    public ResultVo<List<Books>> query(@RequestBody Map<String, String> param) {
        String bookName = param.get("bookName");
        String bookAuthor = param.get("bookAuthor");
        List<Books> books = booksService.queryBooksByName(bookName, bookAuthor);
        return new ResultVo<>(books).success();
    }

    @PostMapping("/page")
    public PageInfo<Books> findByPage(@RequestParam("pageCode") int pageCode, @RequestParam("pageSize") int pageSize) {
        PageInfo<Books> byPageInfo = booksService.findByPageService(pageCode, pageSize);
        return byPageInfo;
    }
    @PostMapping("/dbook")
    public Map<String,String> deleteboks(@RequestParam("id") int id) {
        Map<String, String> map = new HashMap<>();
        map.put("status", "success");
        map.put("msg", "删除成功");
        int i = booksService.deleteBook(id);
        log.info("删除的条数{}",i);
        return map;
    }

    @PostMapping("/myborrow")
    public ResultVo<List<BooksBorrow>> myborrow(@RequestParam("id") Long id) {
        List<BooksBorrow> booksBorrows = booksBorrowService.selectBooksBorrow(id);
        return new ResultVo<>(booksBorrows).success();
    }

    @PostMapping("/borrow")
    public Map<String, String> borrow(@RequestBody BooksBorrow booksBorrow) {
        Map<String, String> map = new HashMap<>();

        int booknum = booksBorrow.getBookNum() - 1;
        if (booknum<0){
            map.put("status", "success");
            map.put("msg", "库存不足");
            return map;
        }
        int i = booksBorrowService.addBooksBorrow(booksBorrow);
        System.out.println(booknum);
        Books build = Books.builder().bookNum(booknum).id(booksBorrow.getId()).bookName(booksBorrow.getBookName())
                .bookAuthor(booksBorrow.getBookAuthor())
                .bookType(booksBorrow.getBookType())
                .bookRemark(booksBorrow.getBookRemark())
                .bookPrice(Integer.parseInt(booksBorrow.getBookPrice())).build();

        booksService.editBook(build);
        if (i > 0) {
            map.put("status", "success");
            map.put("msg", "借书成功");
        }
        log.info("这是【{}】",booksBorrow);
        return map;
    }

    @PostMapping("/return")
    public Map<String, String> returnbook(@RequestBody BooksBorrow booksBorrow) {
        Map<String, String> map = new HashMap<>();
        int returnbook = booksBorrowService.returnbook(booksBorrow.getId());
        Integer bookNum = booksBorrow.getBookNum()+1;
        Books build = Books.builder().bookNum(bookNum).id(booksBorrow.getBookId()).bookName(booksBorrow.getBookName())
                .bookAuthor(booksBorrow.getBookAuthor())
                .bookType(booksBorrow.getBookType())
                .bookRemark(booksBorrow.getBookRemark())
                .bookPrice(Integer.parseInt(booksBorrow.getBookPrice())).build();
        booksService.editBook(build);
        if (returnbook > 0) {
            map.put("status", "success");
            map.put("msg", "归还成功");
        }
        return map;
    }



}
